<template>
  <div>
    <el-row type="flex" :gutter="16">
      <el-col :span="8" class="text-center">
        <!-- 头像区域 -->

        <div>
          <el-image class="avatar-area" :src="avatar" :preview-src-list="[avatar]"></el-image>
        </div>
        <!-- 角色标签 -->
        <div v-if="form.isAdmin === 1" class="mt-4">
          <el-tag>超级管理员</el-tag>
        </div>
      </el-col>
      <el-col :span="10">
        <el-form ref="form" :model="form" label-width="100px" label-position="top" disabled>
          <el-form-item label="登录账号" prop="username">
            <el-input v-model="form.username" />
          </el-form-item>
          <el-form-item label="真实姓名" prop="realname">
            <el-input v-model="form.realname" />
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="form.phone" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" />
          </el-form-item>
          <el-form-item label="角色" prop="roles">
            <el-input v-model="form.roles" />
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="openCropper">{{ avatar ? '编辑头像' : '上传头像' }}</el-button>
      </el-col>

      <Cropper v-if="cropperVisible" :visible.sync="cropperVisible" @on-success="onSuccessCropper"></Cropper>
    </el-row>
  </div>
</template>

<script>
import Cropper from '@/components/Cropper';
import { detailUserApi } from '@/api/user-api.js';
export default {
  name: 'Profile',
  components: {
    Cropper
  },
  data() {
    return {
      form: {
        realname: '',
        username: '',
        role: [],
        email: null,
        phone: null,
        isAdmin: 0
      },
      avatar: '',

      cropperVisible: false
    };
  },
  computed: {
    userId() {
      return this.$store.state.user.userInfo.userId;
    }
  },
  mounted() {
    this.getDetail();
  },
  methods: {
    openCropper() {
      this.cropperVisible = true;
    },
    onSuccessCropper() {
      this.getDetail();
    },

    async getDetail() {
      try {
        const { data } = await detailUserApi(this.userId);

        for (let key in this.form) {
          if (data.hasOwnProperty(key)) {
            this.form[key] = data[key];
          }
        }

        this.$store.commit('user/SET_AVATAR', data.avatar.url);
        this.avatar = `${process.env.VUE_APP_BASE_API}${data.avatar.url}`;
      } catch (err) {
        console.warn(err);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.avatar-area {
  width: 240px;
  height: 240px;
  border-radius: 50%;
}
</style>
